﻿using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace mAdcOW.SharePoint.ChartPicker
{
    public class ExcelPickerEditorPart : EditorPart
    {
        private readonly TextBox _chartName = new TextBox { ID = "chartName", ClientIDMode = ClientIDMode.Static };
        private readonly HtmlSelect _chartPicker = new HtmlSelect { ID = "chartPicker", ClientIDMode = ClientIDMode.Static };
        private readonly TextBox _excelUrl = new TextBox { ID = "excelUrl", ClientIDMode = ClientIDMode.Static };
        private readonly TextBox _height = new TextBox { ID = "imgheight", ClientIDMode = ClientIDMode.Static };
        private readonly TextBox _width = new TextBox { ID = "imgwidth", ClientIDMode = ClientIDMode.Static };

        // Declare a reference to the Tab Editor Web Part
        private ExcelViewer excelViewerWebPart;

        public ExcelPickerEditorPart()
        {
            Title = "Excel Configuration";
        }

        public override bool ApplyChanges()
        {
            excelViewerWebPart = (ExcelViewer)WebPartToEdit;

            // Set the Web Part's properties
            excelViewerWebPart.ExcelUrl = _excelUrl.Text;

            string chartName = string.Empty;
            string chartKey = Page.Request.Form.AllKeys.SingleOrDefault(key => key.EndsWith(_chartPicker.UniqueID));
            if (!string.IsNullOrWhiteSpace(chartKey)) chartName = Page.Request[chartKey];

            excelViewerWebPart.SelectedChart = _chartName.Text = chartName;
            int height;
            int.TryParse(_height.Text, out height);
            excelViewerWebPart.ImageHeight = height;
            int width;
            int.TryParse(_width.Text, out width);
            excelViewerWebPart.ImageWidth = width;
            return true;
        }

        public override void SyncChanges()
        {
            // sync with the new property changes here
            EnsureChildControls();

            excelViewerWebPart = (ExcelViewer)WebPartToEdit;

            // Read the settings from the Web Part
            _excelUrl.Text = excelViewerWebPart.ExcelUrl;
            _chartName.Text = excelViewerWebPart.SelectedChart;
            _height.Text = excelViewerWebPart.ImageHeight.ToString();
            _width.Text = excelViewerWebPart.ImageWidth.ToString();
        }

        protected override void CreateChildControls()
        {
            Controls.Clear();
            ClientScriptManager cm = Page.ClientScript;
            if (!cm.IsClientScriptIncludeRegistered("asset"))
            {
                cm.RegisterClientScriptInclude(typeof(ExcelPickerEditorPart), "asset", "_layouts/15/AssetPickers.js");
            }

            var assetPickerScript = new Literal
                                        {
                                            Text =
                                                "<script type='text/javascript' src='_layouts/15/AssetPickers.js'></script>"
                                        };
            var executorScript = new Literal
                                     {
                                         Text =
                                             "<script type='text/javascript' src='_layouts/15/sp.requestexecutor.js'></script>"
                                     };
            var restScript = new Literal { Text = Template.restScript };
            Controls.Add(assetPickerScript);
            Controls.Add(executorScript);
            Controls.Add(restScript);

            string strRelativeWebURL = SPEncode.HtmlEncode(SPContext.Current.Web.ServerRelativeUrl);
            if (strRelativeWebURL.Trim() == "/")
            {
                strRelativeWebURL = ""; //blank browses the root spweb
            }
            string strAssetPickerConfig = string.Format(@"
                                                        <script type='text/javascript'>
                                                        with(new AssetPickerConfig('testAssetPickerObj'))
                                                        {{
                                                             DefaultAssetImageLocation='';
                                                             CurrentWebBaseUrl='{0}';
                                                             OverrideDialogFeatures='';
                                                             OverrideDialogTitle='';
                                                             OverrideDialogDesc='';
                                                             OverrideDialogImageUrl='';
                                                             AssetUrlClientID='{1}';
                                                             AssetTextClientID='';
                                                             UseImageAssetPicker=false;
                                                             DefaultToLastUsedLocation=true;
                                                             DisplayLookInSection=true;
                                                             ReturnCallback = null;}}
                                                            </script>",
                                                        strRelativeWebURL,
                                                        _excelUrl.ClientID);

            var assetScript = new Literal();
            assetScript.Text = strAssetPickerConfig;
            Controls.Add(assetScript);

            var browseBtn = new Button();
            browseBtn.Text = "...";
            browseBtn.OnClientClick = "APD_LaunchAssetPickerUseConfigCurrentUrl('testAssetPickerObj'); return false;";
            browseBtn.Style["min-width"] = "0em";

            var urlHeader = new Literal { Text = "Url<br/>" };
            Controls.Add(urlHeader);
            Controls.Add(_excelUrl);
            Controls.Add(browseBtn);
            var chartHeader = new Literal { Text = "<br/>Pick Chart<br/>" };
            Controls.Add(chartHeader);
            Controls.Add(_chartPicker);
            var activeChartHeader = new Literal { Text = "<br/>Active Chart<br/>" };
            Controls.Add(activeChartHeader);
            Controls.Add(_chartName);

            var heightHeader = new Literal { Text = "<br/>Image Height<br/>" };
            Controls.Add(heightHeader);
            Controls.Add(_height);

            var widthHeader = new Literal { Text = "<br/>Image Width<br/>" };
            Controls.Add(widthHeader);
            Controls.Add(_width);
        }
    }
}